package com.kehutong.payfees.admin;

import com.kehutong.common.urlconfig.WebUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.payfees.entity.ChargeFeeType;
import com.kehutong.payfees.util.BasicClient;
import org.coraframework.authz.HasPermission;
import org.coraframework.bean.valid.ValidResult;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;

import com.kehutong.payfees.entity.ChargeSundry;

import java.util.List;

@MvcAction
@ReqMapping("/admin/charge/sundry")
public class ChargeSundryAction  {

    @Inject
    private JdbcSession sqlSession;
    @Inject
    private WebUrlConfig webUrlConfig;
    @Inject
    private BasicClient basicClient;


    @HasPermission("charge:sundry:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {

        Page<ChargeSundry> page = sqlSession.findPage(ChargeSundry.class)
                .eq(jsonObject, "communityNo", "roleId", "feeTypeId")
                .eq("deleted", false)
                .order("status", "asc")
                .order("createTime", "desc")
                .page(jsonObject)
                .exe();

        return Result.success(page);
    }

    @HasPermission("charge:sundry:view")
    @ReqMapping("/get")
    public Object get(String id) {
        final ChargeSundry chargeSundry = Pool.get(ChargeSundry.class, id);
        if (Objects.isNull(chargeSundry)) {
            return Result.error(-1, "该数据不存在！");
        }
        return Result.success(chargeSundry);
    }

    @Bean(newInstance=true, copy=true)
    @HasPermission("charge:sundry:edit")
    @ReqMapping("/save")
    public Object save(Token token, ChargeSundry chargeSundry, ValidResult result) throws Exception {
        if (result.hasError("remark", "status", "feeType", "roleId", "roleName")) {
            return Result.error(0, result.getErrorMessage());
        }

        chargeSundry.setStatus(false);
        chargeSundry.setDeleted(false);

        setDepartmentNo(chargeSundry, token.getCompanyNo());

        sqlSession.insert(chargeSundry);
        return Result.success();
    }

    @Bean(copy=true)
    @HasPermission("charge:sundry:edit")
    @ReqMapping("/update")
    public Object update(Token token, ChargeSundry chargeSundry, ValidResult result) throws Exception {
        if (result.hasError("remark", "status", "feeType", "roleId", "roleName")) {
            return Result.error(0, result.getErrorMessage());
        }

        ChargeFeeType feeType = Pool.get(ChargeFeeType.class,chargeSundry.getFeeTypeId());

        if(Objects.nonNull(feeType.getFeetype())){
            chargeSundry.setFeeType(feeType.getFeetype().getDesc());
        }else{
            chargeSundry.setFeeType(null);
        }

        setDepartmentNo(chargeSundry, token.getCompanyNo());

        sqlSession.updateById(chargeSundry);
        return Result.success();
    }

    @HasPermission("charge:sundry:edit")
    @ReqMapping("/setStatus")
    public Object setStatus(String id, Boolean type) {
        final ChargeSundry chargeSundry = Pool.get(ChargeSundry.class, id);
        if (Objects.nonNull(chargeSundry)) {
            chargeSundry.setStatus(type);
            sqlSession.updateById(chargeSundry);
        }

        return Result.success();
    }

    @HasPermission("charge:sundry:edit")
    @ReqMapping("/delete")
    public Object delete(String id) {
        final ChargeSundry chargeSundry = Pool.get(ChargeSundry.class, id);
        if (Objects.nonNull(chargeSundry)) {
            chargeSundry.setDeleted(true);
            sqlSession.updateById(chargeSundry);
        }

        return Result.success();
    }

    @HasPermission("charge:sundry:view")
    @ReqMapping("/download")
    public String download(Token token, String id) {
        final ChargeSundry chargeSundry = Pool.get(ChargeSundry.class, id);

        StringBuffer url = new StringBuffer()
                .append(webUrlConfig.getUrl("/pay/sundry/"))
                .append("?id=").append(chargeSundry.getId())
                .append("&companyNo=").append(token.getCompanyNo());

        return url.toString();
    }


    private void setDepartmentNo(ChargeSundry entity, String companyNo) throws Exception {
        JSONObject community = basicClient.getCommunityById(companyNo,
                entity.getCommunityNo());
        if(Objects.nonEmpty(community)){
            String parent_id = community.getString("parent_id");
            if(Objects.nonEmpty(parent_id)){
                entity.setDepartmentNo(parent_id);
            }
            JSONArray parent_ids = community.getJSONArray("parent_ids");
            if(Objects.nonEmpty(parent_ids)){
                List<String> departmentNos = JSONObject.parseArray(parent_ids.toJSONString(), String.class);
                entity.setDepartmentNos(departmentNos);
            }
        }
    }
}
